import { Button, Form, Input, message, Progress, Result, Tooltip } from 'antd'
import React, { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'

// import MyUpload from '@/components/upload'
// import Footers from '@/layout/footer'
import imgSrc from '@/assets/u3.png'
import useRsa from '@/hooks/useRsa'
import request from '@/utils/axios'
const formItemLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 8
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      offset: 4,
      span: 16
    }
  }
}
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 16,
      offset: 4
    }
  }
}

// import styles from './index.module.less'
const Register: React.FC = () => {
  // const [flag, setFlag] = useState<number>(0)
  const [pwd, setPwd] = useState<number>(0) // 密码长度
  const [success, setSuccess] = React.useState<boolean>(false) //注册成功标志
  const [telPhone, setTelPhone] = useState<string>('') //手机号码
  const rasEncrypt = useRsa()
  const navigate = useNavigate() //路由编程导航

  useEffect(() => {
    console.log('hello register')
    return () => {
      setSuccess(false)
    }
  }, [])

  //注册获取验证码
  // const onGetCaptcha = () => {
  //   countRef.current = 29
  //   setCount(countRef.current)
  //   const interval = setInterval(() => {
  //     setCount(--countRef.current)
  //     if (countRef.current === 0) {
  //       clearInterval(interval)
  //     }
  //   }, 1000)
  //   sendCode({
  //     phone: telPhone
  //   })
  //     .then((res: any) => {
  //       if (res.code === 1000) {
  //         message.success('验证码已发送')
  //       } else {
  //         message.error(res.msg)
  //       }
  //     })
  //     .catch((error) => {
  //       console.log('error:', error)
  //       message.error(error.msg)
  //     })

  //   // if (res.code === 1000) {
  //   //   message.success('验证码已发送')
  //   // } else {
  //   //   message.error('res.msg')
  //   // }
  // }
  //导航去登录页面
  const goToLogin = () => {
    navigate('/login')
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }
  const onFinish = (values: any) => {
    values.password = rasEncrypt(values.password)
    request
      .post('/ivr/user/register', values)
      .then(() => {
        setSuccess(true)
      })
      .catch((err) => {
        console.log(err)
        // message.error(err.msg)
      })
    // userRegister({
    //   phone: values.phone,
    //   password: values.password,
    //   code: values.code,
    //   realname: values.realname,
    //   email: values.email,
    //   type: values.type,
    //   companyName: values.companyName,
    //   idCard: values.idCard?.map((item: Picture) => baseUrl + item.id),
    //   enterpriseCard: values.enterpriseCard?.map(
    //     (item: Picture) => baseUrl + item.id
    //   )
    // })
    //   .then((res: any) => {
    //     console.log(res)
    //     if (res.code === 1000) {
    //       setSuccess(true)
    //     } else {
    //       message.error(res.msg)
    //     }
    //   })
    //   .catch((err) => {
    //     console.log(err)
    //     message.error(err.msg)
    //   })
    // // setSuccess(true)
  }
  const onPwdChange = (e: any) => {
    console.log(e.target.value as string)
    const password = e.target.value.trim()
    setPwd(() => password.length)
    console.log(pwd)
  }

  return (
    <div className="w-100% h-100% bg-#f0f2f5 login">
      <div className="w-500px min-h-screen mx-auto p-40px">
        {/* <div className="flex flex-col items-center mb-40px">
          <div className="text-22px text-#333 leading-50px mt-40px">
            数据库管理系统
          </div>
        </div> */}
        <div className="flex flex-col mb-30px items-center">
          <div className="w-320px flex justify-center items-center">
            <img className="w-45px h-45px mr-30px" src={imgSrc} alt="404" />{' '}
            <div className="flex-col flex items-start">
              <span className="text-center  text-#ccc">中国人民解放军</span>
              <span className="text-center text-20px text-#ccc">
                海军指挥学院
              </span>
            </div>
          </div>
          <div className="inline mt-20px text-30px text-#333 text-center">
            数据库管理系统
          </div>{' '}
        </div>
        {success ? (
          <Result
            status="success"
            title={
              <>
                <div>您的账户: {telPhone}注册成功!</div>
                <div>请联系管理员启用</div>
              </>
            }
            extra={[
              <Button type="primary" key="console" onClick={goToLogin}>
                返回登录
              </Button>
            ]}
          />
        ) : (
          <>
            <div>
              <Form
                {...formItemLayout}
                name="register"
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                initialValues={{
                  prefix: '86'
                }}
                scrollToFirstError
              >
                <Form.Item
                  name="userName"
                  // label="Nickname"
                  // tooltip="What do you want others to call you?"
                  rules={[
                    {
                      required: true,
                      message: '请输入您的姓名!',
                      whitespace: true
                    }
                    // {
                    //   pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/,
                    //   message: '请输入2-30个中文字符'
                    // }
                  ]}
                >
                  <Input placeholder="您的姓名，2-30个字符，必填" />
                </Form.Item>
                <Form.Item
                  name="loginName"
                  // label="Phone Number"
                  rules={[
                    {
                      required: true,
                      message: '请输入账号!'
                    }
                    // {
                    //   pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, //正则校验手机号
                    //   message: '请输入正确的手机号'
                    // }
                  ]}
                >
                  <Input
                    placeholder="请输入账号"
                    style={{
                      width: '100%'
                    }}
                    onChange={(e) => {
                      setTelPhone(e.target.value)
                    }}
                  />
                </Form.Item>

                <Tooltip
                  placement="right"
                  title={
                    <>
                      <div>
                        <div
                          style={
                            pwd < 6 ? { color: 'red' } : { color: '#72c140' }
                          }
                        >
                          强度：{pwd < 6 ? '太短' : '安全'}
                        </div>
                        <Progress
                          percent={(pwd / 16) * 100}
                          showInfo={false}
                          status={pwd < 6 ? 'exception' : 'success'}
                        />
                      </div>
                      <span style={{ color: '#5a5a5a' }}>
                        请至少输入 6 个字符。请不要使用容易被猜到的密码。
                      </span>
                    </>
                  }
                  trigger="focus"
                  color={'white'}
                >
                  <Form.Item
                    name="password"
                    // label="Password"
                    rules={[
                      {
                        required: true,
                        message: '请输入您的密码!'
                      },
                      {
                        pattern: /^\S{6,16}$/,
                        message: '请输入6-16位密码,区分大小写'
                      }
                    ]}
                    hasFeedback
                  >
                    <Input.Password
                      placeholder="6-16位密码，区分大小写"
                      onChange={onPwdChange}
                    />
                  </Form.Item>
                </Tooltip>

                <Form.Item
                  name="confirm"
                  // label="Confirm Password"
                  dependencies={['password']}
                  hasFeedback
                  rules={[
                    {
                      required: true,
                      message: '确认您的密码!'
                    },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('password') === value) {
                          return Promise.resolve()
                        }

                        return Promise.reject(
                          new Error('您两次输入的密码不一致!')
                        )
                      }
                    })
                  ]}
                >
                  <Input.Password placeholder="确认密码" />
                </Form.Item>

                {/* <Form.Item
                  name="email"
                  // label="E-mail"
                  rules={[
                    {
                      type: 'email',
                      message: '您输入的电子邮箱无效!'
                    },
                    {
                      required: true,
                      message: '请输入您的邮箱!'
                    }
                  ]}
                >
                  <Input placeholder="电子邮箱，用于找回密码，必填" />
                </Form.Item> */}

                {/* <Form.Item>
                  <div id="awsc" style={{ position: 'inherit' }}></div>
                </Form.Item> */}
                <Form.Item {...tailFormItemLayout}>
                  <div className="flex justify-between items-center">
                    <Button
                      style={{ width: 100 }}
                      type="primary"
                      htmlType="submit"
                    >
                      注册
                    </Button>
                    <a onClick={goToLogin}>使用已有账户登录</a>
                  </div>
                </Form.Item>
              </Form>
            </div>
          </>
        )}
      </div>
      {/* <Footers /> */}
    </div>
  )
}
export default Register
